const multer = require("multer");
const Mao = require("multer-aliyun-oss");
const { UnsupportedMediaType } = require("http-errors");
const { fail } = require("../utils/response");
const { v4: uuidv4 } = require("uuid");
const OSS = require("ali-oss");

const ossConfig = {
  region: process.env.region, // 你的OSS区域
  accessKeyId: process.env.accessKeyId, // 替换为你的AccessKeyId
  accessKeySecret: process.env.accessKeySecret, // 替换为你的AccessKeySecret
  bucket: process.env.bucket, // 替换为你的Bucket名称
};

// 配置阿里云OSS
const uploadConfig = {
  config: ossConfig,
  // 可选：自定义文件名
  filename: function (req, file, cb) {
    // console.log("file==", file);

    // 使用原始文件名，或者自定义
    // cb(null, file.originalname);
    // 或者添加时间戳防止重名
    cb(null, uuidv4() + "-" + file.originalname);
  },
};
// aliyun-oss SDK client
const client = new OSS(ossConfig);

const upload = multer({
  storage: Mao(uploadConfig),
  fileFilter(req, file, cb) {
    if (file.mimetype.startsWith("image/")) {
      cb(null, true);
    } else {
      cb(new UnsupportedMediaType("仅支持图片文件"), false);
    }
  },
  limits: {
    fileSize: 5 * 1024 * 1024,
  },
});
const singleImgUpload = upload.single("file");
const moreImgsUpload = upload.array("files");
// oss SDK api
const ossSdk = {
  async delete(fullName) {
    return await client.deleteMulti(fullName, {quiet: true})
  },
  async deleteMulti(fullNameArr) {
    return await client.deleteMulti(fullNameArr, {quiet: true})
  }
}

module.exports = {
  client,
  ossSdk,
  upload,
  singleImgUpload,
  moreImgsUpload,
};
